package com.blockmeta.bbs.businesslibrary.adapter;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import androidx.annotation.Nullable;

import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.SpanUtils;
import com.blockmeta.bbs.baselibrary.utils.FormatUtil;
import com.blockmeta.bbs.baselibrary.utils.LoadPicUtil;
import com.blockmeta.bbs.baselibrary.utils.RegexUtil;
import com.blockmeta.bbs.baselibrary.utils.TimeUtil;
import com.blockmeta.bbs.businesslibrary.R;
import com.blockmeta.bbs.businesslibrary.arouter.RouterHelper;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.business.UmengEvent;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.pojo.BBSListZanPOJO;
import com.blockmeta.bbs.businesslibrary.util.DeepLinkUtils;
import com.blockmeta.bbs.businesslibrary.util.RouterActivityHelper;
import com.blockmeta.bbs.businesslibrary.widget.BbsGroupTag;
import com.blockmeta.bbs.businesslibrary.widget.DebateBar;
import com.blockmeta.bbs.businesslibrary.widget.DebateView;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by author on 2018/1/3.
 */

public class BBSListAdapter extends BaseMultiItemQuickAdapter<BBSListZanPOJO.ListBean, BaseViewHolder> {
    private Context mContext;
    private List<BBSListZanPOJO.ListBean> tagDatas = new ArrayList<>();

    private DebateBar.OnVoteBarClickListener mOnVoteBarClickListener;
    private BBSListZanPOJO.ListBean mDebateBean;
    private OnGroupTagClickListener mOnGroupTagClickListener;
    /**判断是不是最新Tab下的列表*/
    private boolean isNewestTab;
    /**当前排序是否按回帖时间排序，用来判断是否展示回帖时间，否则展示发帖时间*/
    private boolean isReplySort = true;
    private String searchKeyWord;


    public BBSListAdapter(@Nullable List<BBSListZanPOJO.ListBean> data, Context mContext) {
        super(data);
        //tou
        addItemType(BBSListZanPOJO.ListBean.Head, R.layout.item_bbs_header);
        //body
        addItemType(BBSListZanPOJO.ListBean.Body, R.layout.item_bbs_list_item_zan);
        //advertising
        addItemType(BBSListZanPOJO.ListBean.ADVERTISING,R.layout.item_bbs_list_item_ad);
        //辩论
        addItemType(BBSListZanPOJO.ListBean.ARGUE,R.layout.item_bbs_list_item_vote);
        this.tagDatas = data;
        this.mContext = mContext;
    }

    public void setSearchKeyWord(String searchKeyWord) {
        this.searchKeyWord = searchKeyWord;
    }

    @Override
    protected void convert(BaseViewHolder helper, final BBSListZanPOJO.ListBean item) {
        int viewType = helper.getItemViewType();
        switch (viewType) {
            case BBSListZanPOJO.ListBean.Head:
                initHead(helper, item);
                break;
            case BBSListZanPOJO.ListBean.Body:
                initBody(helper, item);
                break;
            case BBSListZanPOJO.ListBean.ARGUE:
                initArgue(helper,item);
                break;
            case BBSListZanPOJO.ListBean.ADVERTISING:
                initAd(helper,item);
                break;
            default:
                break;
        }
    }

    private void initArgue(BaseViewHolder helper, final BBSListZanPOJO.ListBean itemBean) {
        mDebateBean = itemBean;
        ImageView view = helper.getView(R.id.bbs_item_icon);
        Picasso.with(mContext).load(itemBean.getAuthor_info().getAvatar()).placeholder(R.drawable.photo_default).into(view);

        helper.setText(R.id.bbs_item_author, itemBean.getAuthor_info().getName());

        helper.setText(R.id.bbs_item_group, itemBean.getAuthor_info().getGroup_title());

        helper.setText(R.id.bbs_item_registertime, itemBean.getAuthor_info().getDate());

        TextView title = helper.getView(R.id.bbs_item_title);
        //是判断精华
        String digest = itemBean.getDigest();
        //有无附件
        String attachment = itemBean.getAttachment();
        Drawable drawable = "100".equals(itemBean.getType())?mContext.getResources().getDrawable(R.drawable.icon_debate):mContext.getResources().getDrawable(R.drawable.debet_lable);
        initTag(itemBean,title,digest,attachment,drawable);

        TextView tvContent = helper.getView(R.id.bbs_item_content);

        if ("".equals(itemBean.getContent())) {
            tvContent.setVisibility(View.GONE);
        } else {
            tvContent.setVisibility(View.VISIBLE);
            tvContent.setText(RegexUtil.getHightLight(RegexUtil.delHTMLTag(itemBean.getContent()), searchKeyWord));
//            RichText.from(itemBean.getContent()).clickable(false).into(tvContent);
        }

        DebateView debateView = helper.getView(R.id.bbs_item_vote);
        if ("100".equals(itemBean.getType())){
            debateView.setVisibility(View.VISIBLE);
        }else {
            debateView.setVisibility(View.GONE);
        }
        debateView.setViewpoints(itemBean.getAffirmpoint(),itemBean.getNegapoint());
        debateView.setVoteCounts(itemBean.getAffirmdebaters(),itemBean.getNegadebaters());
        if (!TextUtils.isEmpty(itemBean.getImgUrl())){
            debateView.setPic(itemBean.getImgUrl());
        }
        if (itemBean.isDebated()){
            debateView.setVoteActive(itemBean.getUserStand(),true);
        }else {
            debateView.resetState();
        }
        if (mOnVoteBarClickListener!=null) {
            debateView.setVoteClickListener(mOnVoteBarClickListener);
        }

        View item = helper.getView(R.id.item_bbs_main);
        item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UmengEvent.eventStatistics(mContext,Constant.U_BBS_TOP_TOPIC,null);
                RouterHelper.buildPath(RouterPath.BBS_DEBATE_ACTIVITY)
                        .withString("tid",itemBean.getTid()+"")
                        .navigation(mContext);
            }
        });

        View author = helper.getView(R.id.group_author);
        author.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UmengEvent.eventStatistics(mContext,Constant.U_BBS_POST_AUTHOR,null);
                RouterActivityHelper.openUserCenter(mContext, itemBean.getAuthor_info().getId());
            }
        });
    }
    private HashMap<String,String> mAdMap = new HashMap<>();
    private void initAd(final BaseViewHolder helper, final BBSListZanPOJO.ListBean item) {
        ImageView view = helper.getView(R.id.bbs_item_icon);
        Picasso.with(mContext).load(item.getAuthor_info().getAvatar()).placeholder(R.drawable.photo_default).into(view);

        helper.setText(R.id.bbs_item_author, item.getAuthor_info().getName());

        helper.setText(R.id.bbs_item_group, item.getAuthor_info().getGroup_title());

        helper.setText(R.id.bbs_item_registertime, item.getAuthor_info().getDate());

        helper.setText(R.id.bbs_item_title,item.getTitle());

        helper.setGone(R.id.banner_tag,!TextUtils.isEmpty(item.getTag()));
        helper.setText(R.id.banner_tag,item.getTag());

        ImageView adPic = helper.getView(R.id.iv_ad);
        LoadPicUtil.load(item.getImgUrl(),adPic);

        if (item.getOuterUrl()==null) {
            return;
        }
        View itemView = helper.getView(R.id.item_bbs_main);
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAdMap.clear();
                mAdMap.put("Ad_name",item.getTitle());
                mAdMap.put("Ad_type",item.getTag());
                mAdMap.put("Ad_id",item.getId());

                UmengEvent.eventStatistics(mContext,Constant.U_BBS_AD,mAdMap);
                DeepLinkUtils.jumpToTarget(mContext, Uri.parse(DeepLinkUtils.regexUri(item.getOuterUrl())));
            }
        });
        View author = helper.getView(R.id.group_author);
        author.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UmengEvent.eventStatistics(mContext,Constant.U_BBS_POST_AUTHOR,null);
                RouterActivityHelper.openUserCenter(mContext, item.getAuthor_info().getId());
            }
        });
    }

    private void initHead(BaseViewHolder helper, final BBSListZanPOJO.ListBean item) {
        final String type = item.getType();
        helper.getView(R.id.item_bbs_header).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //友盟点击事件统计
                UmengEvent.eventStatistics(mContext,Constant.U_BBS_TOP,null);
                if ("4".equals(type) && item.getFid() != 121) {
                    //活动
                    RouterHelper.startActivity(mContext,RouterPath.ACTIVE_DETAIL_ACTIVITY,item.getTid()+"");
                } else if ("3".equals(type)) {
                    //悬赏
                    RouterHelper.buildPath(RouterPath.BBS_REWARD_ACTIVITY)
                            .withString("tid",item.getTid()+"")
                            .navigation(mContext);
                } else if ("1".equals(type)) {
                    //投票
                    RouterHelper.buildPath(RouterPath.BBS_VOTE_ACTIVITY)
                            .withString("tid",item.getTid()+"")
                            .navigation(mContext);
                } else if (item.getFid() == 121) {
                    //AMA主题帖子
                    if (item.getActivity() == null) {return;}
                    final String dateStatus = FormatUtil.getDateStatus(item.getActivity().getStarttimefrom(), item.getActivity().getStarttimeto());
                    RouterHelper.buildPath(RouterPath.BBS_AMA_EXTEND_ACTIVITY)
                            .withString("tid",item.getTid()+"")
                            .withString(Constant.ONE,item.getActivity().getAttachurl())
                            .withString(Constant.TWO,dateStatus)
                            .navigation(mContext);
                } else if ("5".equals(type)){
                    RouterHelper.buildPath(RouterPath.BBS_DEBATE_ACTIVITY)
                            .withString("tid",item.getTid()+"")
                            .navigation(mContext);
                }else {
                    RouterHelper.buildPath(RouterPath.BBS_DETAIL_ACTIVITY).withString("tid",item.getTid()+"").navigation(mContext);
                }
            }
        });
        helper.setText(R.id.item_bbs_header, RegexUtil.getHightLight(item.getTitle(), searchKeyWord));
    }

    /**
     * 文档说明 见论坛http://192.168.168.75:8090/pages/viewpage.action?pageId=9699344
     *
     * @param helper
     * @param item
     */
    private void initBody(BaseViewHolder helper, final BBSListZanPOJO.ListBean item) {
        final String type = item.getType();
        TextView title = helper.getView(R.id.bbs_item_title);
        final BbsGroupTag bbsGroupTag = helper.getView(R.id.bbs_item_tap);
        View tagClickArea = helper.getView(R.id.v_tag_click_area);
        if (item.getCategory()==null||TextUtils.isEmpty(item.getCategory().getName())||!isNewestTab){
            bbsGroupTag.setVisibility(View.GONE);
        }else {
            bbsGroupTag.setVisibility(View.VISIBLE);
            bbsGroupTag.setTagName(item.getCategory().getName(), Integer.parseInt(item.getCategory().getId()));
        }
        tagClickArea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UmengEvent.eventStatistics(mContext,Constant.U_BBS_POST_NODE,null);
                if (mOnGroupTagClickListener==null){
                    return;
                }
                mOnGroupTagClickListener.onGroupTagClickListener(item,bbsGroupTag.getTabPosition());
            }
        });
        //是判断精华
        String digest = item.getDigest();
        //有无附件
        String attachment = item.getAttachment();
        if (attachment == null) {
            attachment = "0";
        }
        SpannableStringBuilder spannableStringBuilder;
        switch (type) {
            case "0":
                //普通
                switch (attachment) {
                    case "2":
                        //图片附件
                        if ("0".equals(digest)) {
                            spannableStringBuilder = new SpanUtils()
                                                  .append(item.getTitle() + " ")
                                                  .appendImage(mContext.getResources().getDrawable(R.drawable.comment_list_pic), SpanUtils.ALIGN_CENTER)
                                                  .create();
                        } else {
                            spannableStringBuilder = new SpanUtils()
                                                  .appendImage(mContext.getResources().getDrawable(R.drawable.essence_lable), SpanUtils.ALIGN_CENTER)
                                                  .append(" " + item.getTitle() + " ")
                                                  .appendImage(mContext.getResources().getDrawable(R.drawable.comment_list_pic), SpanUtils.ALIGN_CENTER)
                                                  .create();
                        }
                        title.setText(RegexUtil.getHightLight(spannableStringBuilder, searchKeyWord));
                        break;
                    default:
                        if ("0".equals(digest)) {
                            title.setText(RegexUtil.getHightLight(item.getTitle(), searchKeyWord));
                        } else {
                            spannableStringBuilder = new SpanUtils()
                                                  .appendImage(mContext.getResources().getDrawable(R.drawable.essence_lable), SpanUtils.ALIGN_CENTER)
                                                  .append(item.getTitle() + " ")
                                                  .create();
                            title.setText(RegexUtil.getHightLight(spannableStringBuilder, searchKeyWord));

                        }
                        break;
                }


                break;
            case "1":
                //投票  绿色
                initTag(item, title, digest, attachment, mContext.getResources().getDrawable(R.drawable.vote_lable));
                break;
            case "2":
                //商品  黑色
                initTag(item, title, digest, attachment, mContext.getResources().getDrawable(R.drawable.product_lable));
                break;
            case "3":
                //悬赏   橘黄
                initTag(item, title, digest, attachment, mContext.getResources().getDrawable(R.drawable.award_lable));
                break;
            case "4":
                //活动  红色
                initTag(item, title, digest, attachment, mContext.getResources().getDrawable(R.drawable.activity_lable));
                break;
            case "5":
                //辩论  //蓝色
                initTag(item, title, digest, attachment, mContext.getResources().getDrawable(R.drawable.debet_lable));
                break;
            default:
                break;
        }

        TextView tv_content = helper.getView(R.id.bbs_item_content);
        if ("".equals(item.getContent())) {
            tv_content.setVisibility(View.GONE);
        } else {
            tv_content.setVisibility(View.VISIBLE);
            tv_content.setText(RegexUtil.getHightLight(item.getContent(), searchKeyWord));
        }

        ImageView view = helper.getView(R.id.bbs_item_icon);
        Picasso.with(mContext).load(item.getAuthor_info().getAvatar()).placeholder(R.drawable.photo_default).into(view);
        //转换时间
//        helper.setText(R.id.bbs_item_author, item.getAuthor_info().getName() + "/" + CommenUtil.getTimetoHMS(CommonLib.parseInt(item.getLastpost())));
        helper.setText(R.id.bbs_item_author, item.getAuthor_info().getName());
        helper.setText(R.id.bbs_item_count, item.getReplies() + "");
        helper.setText(R.id.bbs_item_views, item.getViews());

        TextView zan = helper.getView(R.id.bbs_item_zan);
        zan.setCompoundDrawablesWithIntrinsicBounds("1".equals(item.getAttitude()) ? R.drawable.zan_red : R.drawable.zan, 0, 0, 0);
        zan.setText(item.getLike() + "");
        helper.setText(R.id.bbs_item_group, item.getAuthor_info().getGroup_title());
        helper.setText(R.id.bbs_item_registertime, item.getAuthor_info().getDate());
        helper.setText(R.id.bbs_item_date, TimeUtil.InforMationTime(isReplySort?FormatUtil.parseInt(item.getLastpost()):FormatUtil.parseInt(item.getPost_date())));
        View view1 = helper.getView(R.id.item_bbs_main);
        view1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UmengEvent.eventStatistics(mContext, Constant.U_BBS_DETAIL, null);
                if ("4".equals(type) && item.getFid() != 121) {
                    //活动
                    RouterHelper.startActivity(mContext,RouterPath.ACTIVE_DETAIL_ACTIVITY,item.getTid()+"");
                } else if ("3".equals(type)) {
                    //悬赏
                    RouterHelper.buildPath(RouterPath.BBS_REWARD_ACTIVITY)
                            .withString("tid",item.getTid()+"")
                            .navigation(mContext);
                } else if ("1".equals(type)) {
                    //投票
                    RouterHelper.buildPath(RouterPath.BBS_VOTE_ACTIVITY)
                            .withString("tid",item.getTid()+"")
                            .navigation(mContext);
                } else if (item.getFid() == 121) {
                    //AMA主题帖子
                    if (item.getActivity() == null) {return;}
                    final String dateStatus = FormatUtil.getDateStatus(item.getActivity().getStarttimefrom(), item.getActivity().getStarttimeto());
                    RouterHelper.buildPath(RouterPath.BBS_AMA_EXTEND_ACTIVITY)
                            .withString("tid",item.getTid()+"")
                            .withString(Constant.ONE,item.getActivity().getAttachurl())
                            .withString(Constant.TWO,dateStatus)
                            .navigation(mContext);
                } else if ("5".equals(type)){
                    RouterHelper.buildPath(RouterPath.BBS_DEBATE_ACTIVITY)
                            .withString("tid",item.getTid()+"")
                            .navigation(mContext);
                }else {
                    RouterHelper.buildPath(RouterPath.BBS_DETAIL_ACTIVITY).withString("tid",item.getTid()+"").navigation(mContext);
                }

            }
        });
        View author = helper.getView(R.id.group_author);
        author.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UmengEvent.eventStatistics(mContext,Constant.U_BBS_POST_AUTHOR,null);
                RouterActivityHelper.openUserCenter(mContext, item.getAuthor_info().getId());
            }
        });
    }

    private void initTag(BBSListZanPOJO.ListBean item, TextView title, String digest, String attachment, Drawable resId) {
        SpannableStringBuilder spannableStringBuilder;
        if ("2".equals(attachment)) {
            if (!"0".equals(digest)&&!TextUtils.isEmpty(digest)) {
                spannableStringBuilder = new SpanUtils()
                                      .appendImage(mContext.getResources().getDrawable(R.drawable.essence_lable), SpanUtils.ALIGN_CENTER)
                                      .append(" ")
                                      .appendImage(resId, SpanUtils.ALIGN_CENTER)
                                      .append(" " + item.getTitle() + " ")
                                      .appendImage(mContext.getResources().getDrawable(R.drawable.comment_list_pic), SpanUtils.ALIGN_CENTER)
                                      .create();

            } else {
                spannableStringBuilder = new SpanUtils()
                                      .appendImage(resId, SpanUtils.ALIGN_CENTER)
                                      .append(" " + item.getTitle() + " ")
                                      .appendImage(mContext.getResources().getDrawable(R.drawable.comment_list_pic), SpanUtils.ALIGN_CENTER)
                                      .create();
            }
        } else {
            if (!"0".equals(digest)&&!TextUtils.isEmpty(digest)) {
                spannableStringBuilder = new SpanUtils()
                                      .appendImage(mContext.getResources().getDrawable(R.drawable.essence_lable), SpanUtils.ALIGN_CENTER)
                                      .append(" ")
                                      .appendImage(resId, SpanUtils.ALIGN_CENTER)
                                      .append(" " + item.getTitle() + " ")
                                      .create();

            } else {
                spannableStringBuilder = new SpanUtils()
                                      .appendImage(resId, SpanUtils.ALIGN_CENTER)
                                      .append(" " + item.getTitle() + " ")
                                      .create();
            }
        }
        title.setText(RegexUtil.getHightLight(spannableStringBuilder, searchKeyWord));
    }

    public void setOnVoteBarClickListener(DebateBar.OnVoteBarClickListener onVoteBarClickListener) {
        mOnVoteBarClickListener = onVoteBarClickListener;
    }

    public BBSListZanPOJO.ListBean getDebateBean() {
        return mDebateBean;
    }

    public interface OnGroupTagClickListener{
        void onGroupTagClickListener(BBSListZanPOJO.ListBean item,int tabPosition);
    }

    public void setOnGroupTagClickListener(OnGroupTagClickListener onGroupTagClickListener) {
        mOnGroupTagClickListener = onGroupTagClickListener;
    }

    public void setNewestTab(boolean newestTab) {
        isNewestTab = newestTab;
    }

    public void setReplySort(boolean replySort) {
        isReplySort = replySort;
    }

}
